<template>
  <el-upload drag :multiple="false" :limit="1" :action="url" :before-upload="beforeUploadHandle" :on-success="successHandle">
    <img v-if="imageUrl" :src="imageUrl" alt="" class="avatar" style="width: 100%; height: 100%;">
    <i v-else class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
  </el-upload>
</template>

<script>
import {getUrl} from '@/utils/request'
import {API_DEFAULT_CONFIG} from '@/config'

export default {
  name: 'fileUpload',
  props: {
    callback: {
      type: Function,
      default: () => {
      }
    },
    imageType: {
      required: true
    },
    attrUrl: {
      // eslint-disable-next-line no-undefined
      type: String || null || undefined
    }
  },
  computed: {
    token() {
      return this.$cookie.get('token')
    }
  },
  watch: {
    attrUrl: {
      handler() {
        if (this.R.isNil(this.attrUrl) || this.R.equals('', this.attrUrl.trim())) {
          this.imageUrl = null
        } else {
          this.imageUrl = `${API_DEFAULT_CONFIG.baseURL}/pub/${this.attrUrl}?token=${this.token}`
        }
      },
      deep: true
    }
  },
  data() {
    return {
      imageUrl: null,
      url: getUrl(`systemApi/${this.imageType}`, {token: this.$cookie.get('token')})
    }
  },
  methods: {
    beforeUploadHandle() {
      return true
    },
    successHandle(response) {
      const url = this.R.prop('imageUrl', response) || this.R.prop('designUrl', response)

      if (!this.R.isNil(url)) {
        this.callback(url)
      }
    }
  },
  mounted() {
  },
  activated() {
  }
}
</script>

<style scoped>
/deep/ .el-upload-dragger{
  height:145px
}
</style>
